/**
 * 
 */
package org.okhati.www.parser;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.okhati.www.model.EmployeeFactory;
import org.okhati.www.model.EmployeeRegistry;
import org.okhati.www.model.Factory;
import org.okhati.www.model.Institution;
import org.okhati.www.model.InstitutionFactory;
import org.okhati.www.model.InstitutionRegistry;
import org.okhati.www.sql.SqlGenerator;

/**
 * @author sbara1
 *
 */
public class Parser {

	private final Map<String, Factory<? extends Object>> factoryMap = new HashMap<String, Factory<? extends Object>>();

	private final InstitutionRegistry institutionRegistry = InstitutionRegistry.getInstance();
	private final EmployeeRegistry employeeRegistry = EmployeeRegistry.getInstance();

	public List<Object> readFile(String type, String file) {
		List<Object> list = new ArrayList<Object>();
		try {
			Workbook workbook = Workbook.getWorkbook(new File(file));
			Sheet [] sheets = workbook.getSheets();
			if(sheets != null && sheets.length > 0) {

			} else {
				System.out.println("Worksheets don't exist. Please specify a different file");
				System.exit(0);
			}
			Sheet currentSheet = sheets[0];
			int rowCount = currentSheet.getRows();
			for(int i = 0; i < rowCount; i++) {
				Object object = factoryMap.get(type).getFactoryObject(currentSheet.getRow(i));
				if(object != null) {
					list.add(object);
				}
			}
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}


	/**
	 * @param <T>
	 * @param string
	 * @param instance 
	 * 2.3
	 * R & D from 14.5 to 14 M
	 * 
	 */
	public <T> void registerFactory(String string, Factory<T> instance) {
		factoryMap.put(string, instance);
	}

	public static void main(String[] args) {
		Parser parser = new Parser();
		parser.registerFactory("Institution", new InstitutionFactory());
		parser.registerFactory("Employee", new EmployeeFactory());
		List<? extends Object> institutionList = parser.readFile("Institution", 
				"/Users/sujan/Dropbox/Okhati/Excel Data/Insitutions Under Institution Type.xls");
		parser.institutionRegistry.setInstitutions((List<Institution>) institutionList);
		List<? extends Object> employeeList = parser.readFile("Employee", 
				"/Users/sujan/Dropbox/Okhati/Excel Data/Insitutions Under Institution Type.xls");
		parser.institutionRegistry.setInstitutions((List<Institution>) employeeList);
		//		registry.printInstitutions();
		//		List<String> districts = registry.getDistricts();
		//		int i = 1;
		//		for (String string : districts) {
		//			System.out.println(i++ + "\t" + string);
		//		}
		//		SqlGenerator.insertDistrictsSql();
		SqlGenerator.insertInstitutionsSql();
	}


}
